//
//  HomeTableViewController.swift
//  TYHWeibo
//
//  Created by IOS on 15/7/28.
//  Copyright © 2015年 IOS. All rights reserved.
//

import UIKit



class HomeTableViewController: BaseTableViewController {

    //微博数据数组
    var statuses: [Status]? {
        didSet {
            tableView.reloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !UserAccount.userLogin {
        visitorView?.setupViewInfo(true, imageName: "visitordiscover_feed_image_smallicon", message: "关注一些人，回这里看看有什么惊喜")
            return
        }
        //注册原型cell
        
        //注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "selectPicture:", name: TYHStatusCellSelectPictureNotification, object: nil)
        
        preparTableView()
        loadData()
        
    }
    
    //注销通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
     func selectPicture(n: NSNotification) {
        print(n)
        
        guard let urls = n.userInfo![TYHStatusCellSelectPictureURLKey] as? [NSURL] else {
            print("url数组获取失败")
            return
        }
        
        guard let indexPath = n.userInfo![TYHStatusCellSelectPictureIndexPathKey] as? NSIndexPath else {
            print("indexPath 获取失败")
            return
        }
        
        let photoBrowserVC = PhotoBrowserViewController(urls: urls, index: indexPath.item)
        
        //自定义转场动画
        photoBrowserVC.transitioningDelegate = self
        photoBrowserVC.modalPresentationStyle = UIModalPresentationStyle.Custom
        
        presentViewController(photoBrowserVC, animated: true, completion: nil)
    
    }
    func preparTableView()
    {
        
        tableView.registerClass(StatusForwardCell.self, forCellReuseIdentifier: StatusCellIdentifier.ForwardCell.rawValue)
        tableView.registerClass(StatusNormalCell.self, forCellReuseIdentifier: StatusCellIdentifier.NormalCell.rawValue)
        tableView.estimatedRowHeight = 300
//        tableView.rowHeight = UITableViewAutomaticDimension
//        tableView.rowHeight = 300
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        refreshControl = TYHRefreshControl()
        
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        
    }
    
    //标记上拉刷新
    var pullupRefreshFlag = false
    
    func loadData() {
        refreshControl?.beginRefreshing()
        
        //
        var since_id = statuses?.first?.id ?? 0
        var max_id = 0
        
        if pullupRefreshFlag {
            since_id  = 0
            max_id = statuses?.last?.id ?? 0
            
        }
        
        Status.loadStatus(since_id, max_id: max_id) { (dataList, error) -> () in
           self.refreshControl?.endRefreshing()
//            print(dataList)
            if error != nil {
                print(error)
                return
            }
            
            let count = dataList?.count ?? 0
            print("刷新了 \(count) 条数据")
            
            if since_id > 0 {
                self.showPulldownTip(count)
            }
            
            if count == 0 {
                return
            }
            
            if since_id > 0 {
                self.statuses = dataList! + self.statuses!
            } else if max_id > 0 {
                self.statuses! += dataList!
                
                self.pullupRefreshFlag = false
            }else {
                self.statuses = dataList
            }
            
            
        }
    }
    
    ///显示下拉刷新数据的条数
    private func showPulldownTip(count: Int) {
        if tipLabel.layer.animationForKey("position") != nil {
            print("动画正在执行 ")
            
            return
        }
        
        tipLabel.text = (count == 0 ) ? "暂时没有新微薄" : "刷新了\(count)条数据"
        
        //标签的初始位置
        let rect = tipLabel.frame
        UIView.animateWithDuration(1.0, animations: { () -> Void in
            
            //自动反转
            UIView.setAnimationRepeatAutoreverses(true)
            
            self.tipLabel.frame = CGRectOffset(rect, 0, 3 * rect.height)
            
            }) { (_) -> Void in
                self.tipLabel.frame = rect
        }
        
    }
    
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statuses?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let status = statuses![indexPath.row]
        
        let cell = tableView.dequeueReusableCellWithIdentifier(StatusCellIdentifier.cellId(status), forIndexPath: indexPath) as! StatusTableViewCell
        cell.status = status
        if indexPath.row == statuses!.count - 1 {
            pullupRefreshFlag = true
            loadData()
        }
        
        return cell
    }
    
    //设置行高
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        
        
        //判断模型中是否缓存了行高
        let status = statuses![indexPath.row]
        
        if let h = status.rowHeight {
//            print("返回缓存行高")
            return h
        }
//        print(indexPath)
        let cell = tableView.dequeueReusableCellWithIdentifier(StatusCellIdentifier.cellId(status)) as! StatusTableViewCell
//        let status = statuses![indexPath.row]
        status.rowHeight = cell.rowHeight(status)
        
        return status.rowHeight!
        
    }
    
    ///懒加载
    private lazy var tipLabel: UILabel = {
        let h: CGFloat = 44
        let lab = UILabel(frame: CGRectMake(0, -2 * h, UIScreen.mainScreen().bounds.width , h))
        lab.backgroundColor = UIColor.orangeColor()
        lab.tintColor = UIColor.whiteColor()
        lab.textAlignment = NSTextAlignment.Center
        
        self.navigationController?.navigationBar.insertSubview(lab, atIndex: 0)
        return lab
    }()
    
    private lazy var isPresented = false

}
///自定义转场动画的协议
extension HomeTableViewController: UIViewControllerTransitioningDelegate {
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = true
        return self
    }
    
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = false
        
        return self
    }
    
}

extension HomeTableViewController: UIViewControllerAnimatedTransitioning {
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 1.5
    }
    
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        
        
        if isPresented {
            let toView = transitionContext.viewForKey(UITransitionContextToViewKey)
            
            transitionContext.containerView()?.addSubview(toView!)
            toView!.alpha = 0
            
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                toView?.alpha = 1.0
                }, completion: { (_) -> Void in
                    transitionContext.completeTransition(true)
            })
            
            
        } else {
            let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                fromView!.alpha = 0
                }, completion: { (_) -> Void in
                    fromView!.removeFromSuperview()
                    
                    transitionContext.completeTransition(true)
            })
        
        }
        
        
    }
    
}







